import CommunityCreateModal from '@/components/CommunityCreateModal';
import {
  deleteCommunity,
  getCommunityList,
  updateCommunityDesc,
} from '@/services/community';
import { CommunityItem } from '@/types/community';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { history, useAccess } from '@umijs/max';
import { Button, Form, Modal, message, Tooltip } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { useRef, useState } from 'react';
import { handleProTableRequest, callApi } from '@/utils/request';
import AuthorizedButton from '@/components/AuthorizedButton'; // 导入权限按钮组件
import './index.less';

export default () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<CommunityItem | null>(
      null,
  );
  const [editForm] = Form.useForm();
  const access = useAccess();
  console.log(access);

  // 编辑描述信息
  const handleEditDesc = (record: CommunityItem) => {
    setCurrentRecord(record);
    editForm.setFieldsValue({ desc: record.desc });
    setEditModalVisible(true);
  };

  // 保存描述信息
  const handleSaveDesc = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentRecord) {
        const result = await callApi(
            () => updateCommunityDesc(currentRecord.id, values.desc),
            { successMsg: '描述信息更新成功', errorMsg: '描述信息更新失败' }
        );

        if (result) {
          setEditModalVisible(false);
          actionRef.current?.reload();
        }
      }
    } catch (error) {
      console.error('更新失败:', error);
    }
  };

  // 处理小区创建成功
  const handleCommunityCreateSuccess = () => {
    setCreateModalVisible(false);
    actionRef.current?.reload();
  };

  // 删除小区
  const handleDelete = (record: CommunityItem) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除小区"${record.communityName}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const result = await callApi(
            () => deleteCommunity(record.id),
            { successMsg: '删除成功', errorMsg: '删除失败' }
        );

        if (result) {
          actionRef.current?.reload();
        }
      },
    });
  };

  // 跳转到房屋列表并带上小区筛选
  const handleGoToHouseList = (communityName: string) => {
    history.push(`/house_manage/house_list?communityName=${communityName}`);
  };

  const columns: ProColumns<CommunityItem>[] = [
    {
      title: '城市',
      dataIndex: 'cityName',
      fixed: 'left',
      width: 100,
    },
    {
      title: '小区名称',
      dataIndex: 'communityName',
      fixed: 'left',
      width: 150,
    },
    {
      title: '小区地址',
      dataIndex: 'address',
      width: 250,
    },
    {
      title: '房屋数',
      dataIndex: 'houseCount',
      width: 100,
      search: false,
      render: (_, record) => {
        if (record.houseCount > 0) {
          return (
              <a onClick={() => handleGoToHouseList(record.communityName)}>
                {record.houseCount}
              </a>
          );
        }
        return record.houseCount;
      },
    },
    {
      title: '建筑信息',
      dataIndex: 'buildingInfo',
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: '小区描述',
      dataIndex: 'desc',
      width: 300,
      search: false,
      ellipsis: true,
      onCell: () => {
        return {
          style: {
            maxWidth: 300,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <AuthorizedButton
            key="edit"
            code="community_list_edit_btn" // 替换为实际的权限码
            onClick={() => handleEditDesc(record)}
        >
          编辑描述
        </AuthorizedButton>,
        <AuthorizedButton
            key="delete"
            code="community_list_delete_btn" // 替换为实际的权限码
            onClick={() => handleDelete(record)}
            danger
        >
          删除
        </AuthorizedButton>,
      ],
    },
  ];

  return (
      <PageContainer
          header={{
            title: '',
          }}
      >
        <ProTable<CommunityItem>
            rowKey="id"
            actionRef={actionRef}
            request={async (params) => {
              const formValues = form.getFieldsValue();
              const queryParams = {
                ...formValues,
                current: params.current,
                pageSize: params.pageSize,
                cityName: params.cityName,
                communityName: params.communityName,
              };

              return handleProTableRequest<CommunityItem>(
                  () => getCommunityList(queryParams),
                  { errorMsg: '获取小区列表失败' }
              );
            }}
            columns={columns}
            scroll={{ x: 'max-content' }}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            toolbar={{
              actions: [
                <AuthorizedButton
                    key="community-list-add-btn"
                    code="community_list_add_btn" // 替换为实际的权限码
                    type="primary"
                    onClick={() => setCreateModalVisible(true)}
                >
                  新建小区
                </AuthorizedButton>,
              ],
            }}
            tableLayout="fixed"
            search={{
              className: 'search-form',
            }}
        />

        {/* 编辑描述弹窗 */}
        <Modal
            title="编辑小区描述"
            open={editModalVisible}
            onOk={handleSaveDesc}
            onCancel={() => setEditModalVisible(false)}
            okText="保存"
            cancelText="取消"
            width={600}
        >
          <Form form={editForm} layout="vertical">
            <Form.Item
                label="小区描述"
                name="desc"
                rules={[{ required: true, message: '请输入小区描述' }]}
            >
              <TextArea
                  rows={4}
                  placeholder="请输入小区描述，例如：距离地铁站500米，周边配套齐全"
                  maxLength={200}
                  showCount
              />
            </Form.Item>
          </Form>
        </Modal>

        {/* 创建小区弹窗 */}
        <CommunityCreateModal
            visible={createModalVisible}
            onCancel={() => setCreateModalVisible(false)}
            onSuccess={handleCommunityCreateSuccess}
            city=""
        />
      </PageContainer>
  );
};